from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from .. import models
from ..models import Books
import os
from . import TypesViews
from django.core.paginator import Paginator

# 后台图书商品列表
def index(request):
    # 获取所有的图书商品信息
    data = models.Books.objects.filter()
    p = Paginator(data,3)
    inx_p = request.GET.get('page',1)
    # 获取当前页码数据
    userlist = p.get_page(inx_p)

    context = {'data':userlist}
    return render(request,'myadmin/books/index.html',context)

# 后台图书商品添加表单
def add(request):
    types = TypesViews.selectAllTypes()
    context = {'types':types}
    return render(request,'myadmin/books/add.html',context)

# 后台图书商品执行添加
def insert(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    data.pop('typeid')
    # 获取选择的分类ID
    typeid = request.POST.getlist('typeid')
    typeobjs = models.booktype.objects.filter(id__in=typeid)
    # 检测当前是否上传了图片
    if not request.FILES.get('pic',None):
        return HttpResponse(f'<script>alert("请为书籍添加一张封面图"); location.href="history.back();"</script>')
    try:
        # 创建书籍对象，完成添加
        obj = models.Books(**data)
        obj.save()
            # 书籍和分类设置的关系
        obj.typeid.set(typeobjs)

            # 图书的图片处理
        img_obj = models.BookImgs()
        img_obj.bookid = obj
        img_obj.img_url = request.FILES.get('pic',None)
        img_obj.save()

        url = reverse('myadmin_books_index')
        return HttpResponse(f'<script>alert("图书商品添加成功"); location.href="{url}"</script>')
    except:
        url = reverse('myadmin_books_add')
        return HttpResponse(f'<script>alert("图书商品添加失败"); location.href="{url}"</script>')

# 后台图书商品删除
def delete(request):
    try:
        id = request.GET.get('id')
        obj = Books.objects.get(id=id)
        # 判断当前用户是否有上传头像
        try:
            if 'uploads' in obj.img_url:
                os.remove('.'+obj.img_url)
        except:
            return JsonResponse({'code':2,'msg':'头像删除失败'})
        obj.delete()
        return JsonResponse({'code':0,'msg':'删除成功'})
    except:
        return JsonResponse({'code':1,'msg':'删除失败'})
    # return render(request,'myadmin/books/delete.html')

# 后台图书商品编辑
def edit(request):
    try:
        id = request.GET.get('id')
        name = request.GET.get('title')
        obj = models.booktype.objects.get(id=id)
        obj.name = name
        obj.save()
        return JsonResponse({'code':0,'msg':'更新成功'})
    except:
        return JsonResponse({'code':1,'msg':'更新失败'})


# def edit(request):
#     return render(request,'myadmin/books/edit.html')